<?php

namespace app\index\controller;

use AlipayTradeService;
use think\Controller;
use think\Request;

class Order extends Base
{
    // 订单结算
    public function add(Request $request)
    {
        \app\index\model\Order::where('order_sn',"lms158097737943932307")->update(["pay_status"=>1]);

        // 判断用户当前是否登录，
        if(!session("?index_user")){
            $this->error("对不起您还没有登录，请先登录。",'/index/Login/index');
            die;
        }

        $data = $request->param();
        if(empty($data)){
            $this->error("请选择您要购买的商品，",'index/cart/cart');
            die;
        }

        $title = "订单支付";

        // 获取所有的收件人信息
        $user_id = session("index_user.id");
        $address = \app\index\model\Address::where("user_id",$user_id)->select();

        // 商品信息
        $goods = \app\index\model\Cart::getGoods($data['cart_ids']);

        // 输出支付方式
        $pay_type = config("pay_type");

        // 计算商品数量和商品价格
        $goods_price = 0;
        $cart_number = 0;
        foreach($goods as $v)
        {
            $cart_number += $v['cart_number'];
            $goods_price += $v['goods_price'] * $v['cart_number'];
        }

        unset($v);

        return view("order/add",[
            'title' => $title,
            'address' => $address,
            'goods' => $goods,
            'goods_price' => $goods_price,
            'cart_number' => $cart_number,
            'pay_type' => $pay_type
        ]);
    }

    // 添加地址
    public function address(Request $request)
    {
        // 判断用户当前是否登录，
        if(!session("?index_user")){
            $this->error("对不起您还没有登录，请先登录。",'/index/Login/index');
            die;
        }

        $data = $request->param();

        $rule = [
            'consignee|收货人' => "require",
            'address|地址' => "require",
            'phone|手机号' => "require|number",
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        // 判断状态值
        $data['check'] = !empty($data['check']) ? 1 : 0;
        // 判断是那个用户添加
        $data['user_id'] = session("index_user.id");

        \app\index\model\Address::create($data,true);

        $this->success("添加成功",'index/order/add?cart_ids='.$data['cart_ids']);
    }

    // 支付订单
    public function btngoods(Request $request)
    {

        // 判断用户当前是否登录，
        if(!session("?index_user")){
            $this->error("对不起您还没有登录，请先登录。",'/index/Login/index');
            die;
        }

        // 订单编号
        $order_sn = 'lms' . time() . mt_rand(10000000,99999999);

        // 开启事务
        \think\Db::startTrans();

        try{
            // 获取提交地址
            $data = $request->param();

            # 表单验证
            $rule = [
                'cart_ids|购物车id' => 'require',
                'cart_address|地址' => 'require',
                'pay_type|支付方式' => 'require'
            ];

            $validate = new \think\Validate($rule);

            if(!$validate->check($data))
            {
                $this->error($validate->getError());
            }

            // 获取到的购物车数据
            $cart_data = \app\index\model\Cart::getGoods($data['cart_ids']);
            $cart_data = (new \think\Collection($cart_data))->toArray();

            // 求出订单金额
            $goods_sum = 0;
            foreach($cart_data as $value)
            {
                $goods_sum += $value['cart_number'] * $value['goods_price'];

                if($value['cart_number'] > $value['goods_number'])
                {
                    throw new \Exception("商品数量不够",10001);
                }

            }

            unset($value);

            // 用户id
            $user_id = session("index_user.id");

            // 查询用户地址信息
            $address = \app\index\model\Address::where('id',$data['cart_address'])->find();

            $data['order_sn'] = $order_sn;
            $data['consignee_name'] = $address['consignee'];
            $data['consignee_phone'] = $address['phone'];
            $data['consignee_address'] = $address['address'];
            $data['shipping_type'] = "顺丰";
            $data['order_sum'] = $goods_sum;
            $data['user_id'] = $user_id;
            $data['pay_status'] = 0;

            $order = \app\index\model\Order::create($data,true);

            // 记录商品信息表
            $new_order = [];
            foreach($cart_data as $v)
            {
                $row = [
                    'order_id' => $order->id,
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $v['goods_name'],
                    'goods_number' => $v['cart_number'],
                    'goods_price' => $v['goods_price'],
                    'goods_logo' => $v['goods_logo'],
                    'goods_attr' => $v['goods_attr_ids'],
                ];
                $new_order[] = $row;
            }

            unset($v);

            $order_goods = new \app\index\model\OrderGoods();
            $order_goods->saveAll($new_order);


            // 订单完成后 在商品表中减去当前购买的数量
            $goods_ids = [];
            foreach($cart_data as &$v)
            {
                $row = [
                    'id' => $v['goods_id'],
                    'goods_number' => $v['goods_number'] - $v['cart_number']
                ];
                $goods_ids[] = $row;
            }

            $goods = new \app\index\model\Goods();

            $goods->saveAll($goods_ids);

            \app\index\model\Cart::destroy([$data['cart_ids']]);

            // 提交事务
            \think\Db::commit();
        }catch (\Exception $e){

            // 回滚事务
            \think\Db::rollback();

            $code = $e->getCode();
            $msg = $e->getMessage();
            $this->error($msg);
        }

        switch ($data['pay_type']){
            case 'wechat':

                break;
            case 'card':

                break;
            case 'cash':

                break;
            default:
                $html = "<form name='alipayment' id='alipay' action='/plugins/alipay/pagepay/pagepay.php' method='post' style='display:none'>
                            <!-- 订单编号 -->
                            <input id='WIDout_trade_no' name='WIDout_trade_no' value='{$order_sn}'/>
                            <!-- 商场 -->
                            <input id='WIDsubject' name='WIDsubject' value='默生'/>
                            <!-- 总金额 -->
                            <input id='WIDtotal_amount' name='WIDtotal_amount' value='{$goods_sum}'/>
                            <!-- 商品信息 -->
                            <input id='WIDbody' name='WIDbody' value='哈哈哈'/>
                        </form><script>document.getElementById('alipay').submit()</script>";
                echo $html;
                break;
        }
        $this->success("支付成功",'index/index/index');
    }

    // 异步通知地址
    public function ybAlipy()
    {
        $data = request()->param();

        require_once './plugins/alipay/config.php';
        require_once './plugins/alipay/pagepay/service/AlipayTradeService.php';

        $alipaySevice = new \AlipayTradeService($config);

        $alipaySevice->writeLog(var_export($data,true));
        $result = $alipaySevice->check($data);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if($result) {
            // 验签成功
            // 支付交易成功，此时状态是可以被操作的 比如发起退款
            if($data['trade_status'] == "TRADE_SUCCESS"){

                // 还没有处理过  修改订单状态
                $order_sn = $data['out_trade_no'];
                $order = \app\index\model\Order::where('order_sn', $order_sn)->find();

                $alipaySevice->writeLog("order对象：".$order);

                // 检测是否为空
                if(empty($order))
                {
                    $alipaySevice->writeLog("没有查到订单编号：".$order_sn);
                    echo 'fail';
                    die;
                }

                // 检测订单和支付信息是否匹配
                if($order['order_sum'] != $data['total_amount']){
                    $alipaySevice->writeLog("支付金额和订单总金额不一致，支付金额：" . $data['total_amount'] . "订单金额：".$order['order_sum']);
                    echo "fail";
                    die;
                }

                $order->pay_status = 1;
                $order->save();

                $alipaySevice->writeLog("更新之后order对象：".$order);

                echo "success";
                die;

            // 此时交易完成，不支持退款
            }else if($data['trade_status'] == "TRADE_FINISHED"){

                echo "success";
                die;
            }
        }else{

            // 验签失败
            $alipaySevice->writeLog("验签失败");
            echo 'fail';
            die;
        }
    }

    // 支付结果页 支付宝的同步跳转地址
    public function tbAlipy(){

        $data = request()->param();

        // 验证是否成功
        require_once("./plugins/alipay/config.php");
        require_once './plugins/alipay/pagepay/service/AlipayTradeService.php';

        $alipaySevice = new \AlipayTradeService($config);

        $result = $alipaySevice->check($data);

        if($result){

            $title = "支付成功";

            $order = \app\index\model\Order::where('order_sn',$data['out_trade_no'])->find();

            return view("/order/payok",[
                'title' => $title,
                'order' => $order
            ]);

        }else{

            $title = "支付失败";
            return view("/order/payfail",[
                'title' => $title
            ]);
        }
    }

    // 订单列表页
    public function myOrder()
    {
        // 判断用户当前是否登录，
        if(!session("?index_user")){
            $this->error("对不起您还没有登录，请先登录。",'/index/Login/index');
            die;
        }
        $title = "订单";

        $user_id = session("index_user.id");

        $data = \app\index\model\Order::where('user_id',$user_id)->order('id','DESC')->paginate(5);

        //
        $goods_ids = [];
        foreach($data as $v)
        {
            $v['goods'] = \app\index\model\OrderGoods::where('order_id',$v['id'])->paginate(5);
        }

        return view('/order/myorder',[

            'title' => $title,
            'data' => $data
        ]);
    }

    // 微信支付
    public function wechat()
    {
        $data = request()->param();

        dump($data);
    }
}

